import request from '@/utils/request'
import { removeTokenInfo, setTokenInfo } from '@/utils/storage'

export const setToken = (tokenInfo) => ({
  type: 'login/token',
  payload: tokenInfo,
})
export const removeToken = () => ({ type: 'login/removeToken' })

/**
 * 发送短信验证码
 * @param {*} mobile
 * @returns
 */
export const sendCode = (mobile) => {
  return async (dispatch) => {
    await request.get(`/sms/codes/${mobile}`)
  }
}

/**
 * 请求登录
 * @param {*} data { mobile: xx, code: xx }
 * @returns
 */
export const login = (data) => {
  return async (dispatch) => {
    const res = await request.post('/authorizations', data)
    dispatch(setToken(res.data))
    setTokenInfo(res.data)
  }
}

/**
 * 退出操作
 */
export const logout = () => {
  return (dispatch) => {
    // 1. 清除本地的token
    removeTokenInfo()
    // 2. 清除redux中token => {}
    dispatch(removeToken())
  }
}
